package shuaige.jdk.多线程.信号量;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Semaphore_使用示例1 {
    static ExecutorService executorService = Executors.newCachedThreadPool();

    public static void main(String[] args) {
        final Semaphore semaphore = new Semaphore(3, false);
        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 从这个信号量中获取一个许可，阻塞直到一个信号量可用，或者线程被中断
                        // 获得许可证（如果有）并立即返回，将可用许可证的数量减少一个。
                        semaphore.acquire();
                        String theadName = "线程:" + Thread.currentThread().getName() + "：";
                        System.out.println(theadName + "获得许可");
                        TimeUnit.SECONDS.sleep(1);
                        // 释放许可，将其返回给信号量。
                        semaphore.release();
                        // 返回此信号量中可用的当前许可数。
                        int availablePermits = semaphore.availablePermits();
                        System.out.println(theadName + "允许TASK个数：" + availablePermits);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        // 关闭线程池
        executorService.shutdown();
    }

}
